<template>
    <van-nav-bar title="购物车" left-text="返回" left-arrow fixed @click-left="onBack" v-if="action === 'cart'" />
    <van-nav-bar title="购物车" fixed v-else />

    <div style="height: 50px;"></div>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <!-- 复选框组 -->
            <van-checkbox-group v-model="checkedArr" ref="checkboxGroup">
                <!-- 侧滑块 -->
                <van-swipe-cell v-for="(item,index) in list" :key="item.id">
                    <!-- 商品卡片 -->
                    <van-card :price="item.total" :title="item.product.name" class="goods-card">
                        <!-- 图片 -->
                        <template #thumb>
                            <van-checkbox :name="item.id" @click="onChecked"></van-checkbox>
                            <img :src="item.product.thumbs_cdn" alt="" />
                        </template>
                        <!-- 数量 -->
                        <template #num>
                            <van-stepper v-model="item.nums" :max="item.product.stock"
                                @change="onChange(item.nums, item.id,index)" theme="round" button-size="22" disable-input />
                        </template>

                        <!-- 描述 -->
                        <template #desc>
                            <span>商品单价：￥{{ item.price }}</span>
                        </template>
                    </van-card>
                    <template #right>
                        <van-button square text="删除" type="danger" class="delete-button" @click="onDel(item.id,index)" />
                    </template>
                </van-swipe-cell>
            </van-checkbox-group>
        </van-list>
    </van-pull-refresh>

    <van-submit-bar :class="action !== 'cart' ? 'btn-bottom' : ''" :price="jiage" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="checked" @click="onCheckAll">{{ checked ? '取消全选' : '全选' }}</van-checkbox>
    </van-submit-bar>

    <Footer v-if="action !== 'cart'" />
</template>
<script setup>
import Footer from 'components/common/Footer.vue';
import { getCurrentInstance, ref, reactive, computed } from 'vue';

const { proxy } = getCurrentInstance();
const action = ref(proxy.$route.query.action);
const checked = ref(false);
const list = reactive([]);
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const checkedArr = ref([]);
const checkboxGroup = ref(null);
const listCount = ref(0);
const page = ref(1);
const limit = ref(10);
const business = reactive(proxy.$cookies.get('business') ?? {});


const onRefresh = () => {
    page.value = 1;
    refreshing.value = true;
    list.length = 0;
    loading.value = true;
    onLoad();
}

const onLoad = () => {
    if (!refreshing.value && list.length < listCount.value) {
        page.value = page.value + 1;
    }

    if (refreshing.value) {
        setTimeout(() => {
            refreshing.value = false;
        }, 1500);
    }

    setTimeout(getCartData, 1500);
}

const getCartData = async () => {
    let data = {
        page: page.value,
        limit: limit.value,
        busid: business.id
    }

    let result = await proxy.$Api.cartIndex(data);

    if (result && result.code === 0) {
        finished.value = true;
        return;
    }

    finished.value = false;
    loading.value = false;

    listCount.value = result.data.count;
    list.push(...result.data.list);

    if (list.length === listCount.value) {
        finished.value = true;
        loading.value = false;
        return;
    }
}
//删除购物车的商品
const onDel = (cartid,index) => {
    proxy.$showConfirmDialog({
        title: '删除购物车',
        message: '确认删除购物车记录？'
    }).then(async () => {
        let data = {
            cartid,
            busid: business.id
        }
        let result = await proxy.$Api.cartDelect(data);
        if(result && result.code === 1)
        {
            proxy.$showNotify({
                type:'success',
                message:result.msg,
                duration:2000,
            });

            list.splice(index,1);

            return;
        }else{
            proxy.$showNotify({
                type:'warning',
                message:result.msg,
                duration:2000
            });

            return;
        }
    }).catch((err) => {
        proxy.$showNotify({
            message: '取消删除',
            duration: 2000,
        })
    });
}

//商品增加，商品减少
const onChange = async (nums, cartid ,index) => {
    let data = {
        busid: business.id,
        nums,
        cartid
    }

    let result = await proxy.$Api.cartUpdate(data);

    if (result && result.code === 0) {
        proxy.$showNotify({
            type: 'warning',
            message: result.msg,
            duration: 2000,
        });

        return;
    }
    //价格随数量变化
    let total = parseFloat(list[index].price) * nums;
    //限制两个小数
    list[index].total = total.toFixed(2);
}

//选中后更换全选
const onChecked = () => {
    if (list.length === checkedArr.value.length) {
        checked.value = true;
    } else {
        checked.value = false;
    }
}
// 全选后更换选中
const onCheckAll = () => {
    if (checked.value) {
        checkboxGroup.value.toggleAll(true);
    } else {
        checkboxGroup.value.toggleAll(false);
    }
}

//计算购物车的价格
const jiage = computed(() => {
    //价格初始化
    let jiage = 0;
    if (checkedArr.value.length > 0) {
        for (let item of list) {
            if (checkedArr.value.includes(item.id)) {
                jiage += parseFloat(item.total);
            }
        }
    }
    return jiage * 100;
})

//价格提交按钮
const onSubmit = () => {
    if(checkedArr.value.length <= 0){
        proxy.$showNotify({
            type:'warning',
            message:'请选择结算商品',
            duration:2000
        });
        return false;
    }
    proxy.$router.push({path:'/product/cart/confirm',query:{cartids:checkedArr.value.join(',')}});
};

const onBack = () => {
    proxy.$router.back();
};
</script>

<style>
.btn-bottom {
    bottom: 50px;
}

.goods-card {
    margin: 0;
    background-color: #fff;
}

.delete-button {
    height: 100%;
}

.van-card__thumb {
    display: flex;
    width: auto;
}

.van-card__thumb img {
    width: 88px;
    margin-left: 5px;
}
</style>
